package org.yunai.yfserver.object;

import java.lang.reflect.Array;

/**
 * 键值对
 * User: yunai
 * Date: 13-5-2
 * Time: 下午5:18
 */
public class KeyValuePair<K, V> {

    private static final int PRIME = 31;

    /**
     * key
     */
    private K key;
    /**
     * value
     */
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public void setValue(V value) {
        this.value = value;
    }

    @Override
    public int hashCode() {
        int result = 1;
        result = PRIME * result + (key == null ? 0 : key.hashCode());
        result = PRIME * result + (value == null ? 0 : value.hashCode());
        return result;
    }

    @SuppressWarnings("unchecked")
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        KeyValuePair<K, V> other = (KeyValuePair<K, V>) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }
        if (value == null) {
            if (other.value != null) {
                return false;
            }
        } else if (!value.equals(other.value)) {
            return false;
        }
        return true;
    }

    /**
     * 创建键值对数组
     *
     * @param size 数组大小
     * @param <K>  键类型
     * @param <V>  值类型
     * @return 键值对数组
     */
    @SuppressWarnings("unchecked")
    public static <K, V> KeyValuePair<K, V>[] newInstances(int size) {
        return (KeyValuePair<K, V>[]) Array.newInstance(KeyValuePair.class, size);
    }

    @Override
    public String toString() {
        return "KeyValuePair{" +
                "key=" + key +
                ", value=" + value +
                '}';
    }
}
